//
//  TabbarCustom.m
//  PetApp
//
//  Created by apple on 16/3/10.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "TabbarCustom.h"
#import "TabBarItem.h"
#import "AppDelegate.h"
#import "TableBar.h"

@implementation TabbarCustom

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        [self config];
    }
    
    return self;
}

- (void)config {
    self.backgroundColor = [UIColor whiteColor];
    UIImageView *topLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, -5, [UIScreen mainScreen].bounds.size.width, 5)];
    topLine.image = [UIImage imageNamed:@"tapbar_top_line"];
    [self addSubview:topLine];
}

#pragma mark - 选择下标切换vc
- (void)setSelectedIndex:(NSInteger)index {
    
    for (TabBarItem *item in self.tabBarItems) {
        if (item.tag == index) {
            item.selected = YES;
        } else {
            item.selected = NO;
        }
    }
    
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    
    TableBar *tabBarController = app.tb;
    if (tabBarController) {
        tabBarController.selectedIndex = index;
        if (index != 1) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"pauseAVPlayer" object:nil];
        }
    }
}
#pragma mark - 判断点击事件
- (void)itemSelected:(TabBarItem *)sender {
    if (sender.tabBarItemType != TabBarItemBulge) {
        [self setSelectedIndex:sender.tag];
    } else {
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(tabBarDidSelectedBulgeButton)]) {
                [self.delegate tabBarDidSelectedBulgeButton];
            }
        }
    }
}
#pragma mark - 给视图添加item以及点击方法
- (void)setTabBarItems:(NSArray *)tabBarItems {
    if (_tabBarItems != tabBarItems) {
        _tabBarItems = [tabBarItems copy];
    }
    NSInteger itemTag = 0;
    for (id item in tabBarItems) {
        if ([item isKindOfClass:[TabBarItem class]]) {
            /** 直接选择第一个 */
            if (itemTag == 0) {
                ((TabBarItem *)item).selected = YES;
            }
            [((TabBarItem *)item) addTarget:self action:@selector(itemSelected:) forControlEvents:UIControlEventTouchDown];
            [self addSubview:item];
            /** 给item添加tag */
            if (((TabBarItem *)item).tabBarItemType != TabBarItemBulge) {
                ((TabBarItem *)item).tag = itemTag;
                itemTag++;
            }
        }
    }
}


@end
